package cn.jaye.fabric.application;

import cn.jaye.fabric.application.command.peer.CreatePeerCommand;
import cn.jaye.fabric.application.command.peer.ListMPeerChannelCommand;
import cn.jaye.fabric.application.command.peer.ListPeerCommand;
import cn.jaye.fabric.common.constants.exception.MPeerExceptionEnum;
import cn.jaye.fabric.common.constants.mapping.Table;
import cn.jaye.fabric.common.model.ServiceException;
import cn.jaye.fabric.common.util.KeyIDUtil;
import cn.jaye.fabric.domain.model.MPeer;
import cn.jaye.fabric.domain.repository.PeerRepository;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Jaye
 * @create 2018-05-23 13:48
 */
@Service
public class PeerApplicationService {

    @Autowired
    private PeerRepository peerRepository;

    @Transactional(rollbackFor = Exception.class)
    public boolean create(CreatePeerCommand createPeerCommand) {
        MPeer mPeer = peerRepository.selectOne(new EntityWrapper<MPeer>()
                .eq(Table.Peer.orgId.getFieldValue(), createPeerCommand.getOrgId())
                .eq(Table.Peer.orderId.getFieldValue(), createPeerCommand.getOrderId())
                .eq(Table.Peer.peerName.getFieldValue(), createPeerCommand.getPeerName()));
        if (mPeer != null) {
            throw new ServiceException(MPeerExceptionEnum.PEER_EXIST);
        }
        MPeer newMPeer = new MPeer(createPeerCommand.getOrgId(),
                createPeerCommand.getOrderId(),
                KeyIDUtil.getUUID(),
                createPeerCommand.getPeerName(),
                createPeerCommand.getHostAddress(),
                createPeerCommand.getPort(),
                createPeerCommand.getEventPort(),
                createPeerCommand.getTlsFlag());
        return peerRepository.insert(newMPeer);
    }

    public List<MPeer> list(ListPeerCommand listPeerCommand) {
        String orgId = listPeerCommand.getOrgId();
        Wrapper<MPeer> queryMPeer = new EntityWrapper<MPeer>().eq(Table.Peer.orgId.getFieldValue(), orgId);
        if (StringUtils.isNotBlank(listPeerCommand.getOrderId())) {
            queryMPeer.eq(Table.Peer.orderId.getFieldValue(), listPeerCommand.getOrderId());
        }
        return peerRepository.selectList(queryMPeer);
    }

    public List<MPeer> listPeer(ListMPeerChannelCommand listMPeerChannelCommand) {
        return peerRepository.selectPeerByChannel(listMPeerChannelCommand.getChannelName());
    }
}
